package net.golfklubi.sive;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PropertyListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.validation.validator.RangeValidator;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class SiveHomePage extends MasterPage implements Securable {

    private final String userFiles = new ResourceModel("dirForUsersFiles").getObject();
    private static final String COMPETITIONS_XML = "competitions.xml";

    public SiveHomePage() {
        final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
        final AllGuessesPanel allGuessesPanel = new AllGuessesPanel("allGuessesPanel", getFilesFrom(userFiles), getCompetitionPersisterAndLoader());

        add(allGuessesPanel);
        feedbackPanel.setOutputMarkupPlaceholderTag(true);
        add(feedbackPanel);
        final Form<Void> positionForm = new Form<Void>("positionForm");
        final CompetitionListView competitionListView = new CompetitionListView("competitionList", new CompoundPropertyModel<List<Competition>>(createCompetitionsList()));
        positionForm.add(competitionListView);
        positionForm.add(new Button("submit") {

            @Override
            public void onSubmit() {
                final List<Competition> list = competitionListView.getModelObject();
                try {
                    getCompetitionPersisterAndLoader().saveToFile(list, getFileName());
                    SiveHomePage.this.error("Veikkauksesi tallennettu");
                } catch (final IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
                allGuessesPanel.addOrReplace(new AllGuessesPanel("allGuessesPanel", getFilesFrom(userFiles), getCompetitionPersisterAndLoader()));
                competitionListView.setList(createCompetitionsList());
                throw new RestartResponseException(SiveHomePage.class);
            }

        });
        add(positionForm);
        setOutputMarkupId(true);
    }

    protected String getFileName() {
        return userFiles + File.separator + getUser() + ".xml";
    }

    protected CompetitionPersisterAndLoader getCompetitionPersisterAndLoader() {
        return new CompetitionPersisterAndLoader();
    }

    private IModel<List<File>> getFilesFrom(final String dir) {
        final List<File> filesList = getFilesList(dir);
        return new AbstractReadOnlyModel<List<File>>() {
            @Override
            public List<File> getObject() {
                return filesList;
            }
        };
    }

    private List<File> getFilesList(final String dir) {
        final File[] listFiles = new File(dir).listFiles();
        if (listFiles == null) {
            return Collections.emptyList();
        }
        final List<File> asList = Arrays.asList(listFiles);
        return asList;
    }

    private List<Competition> createCompetitionsList() {
        return getCompetitionPersisterAndLoader().loadFromFile(COMPETITIONS_XML);
    }

    class CompetitionListView extends PropertyListView<Competition> {

        public CompetitionListView(final String id, final IModel<List<Competition>> model) {
            super(id, model);
            setOutputMarkupId(true);
        }

        @Override
        protected void populateItem(final ListItem<Competition> item) {
            final Competition competition = item.getModelObject();
            item.setModel(new CompoundPropertyModel<Competition>(competition));
            final TextField<Integer> rankingGuess = new TextField<Integer>("rankingGuess");
            rankingGuess.setType(Integer.class);
            rankingGuess.add(new RangeValidator<Integer>(0, 300));
            item.add(rankingGuess);
            competition.setNickName(getUser());
            item.add(new Label("competition", competition.name));
            final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(new Locale("fi"));
            item.add(new Label("startDate", competition.getStartDate().toString(dateTimeFormatter)));
            item.add(new Label("siveStopsDate", competition.getStartDate().minusDays(1).toString(dateTimeFormatter)));

        }

    }

    public String getUser() {
        return SiveWebSession.getSiveSession().getUser();
    }
}
